package com.example.webdemo.controller;

import com.example.webdemo.bean.orderitem;
import com.example.webdemo.bean.orders;
import com.example.webdemo.dao.OrderDao;
import com.example.webdemo.dao.OrderItemDao;
import com.example.webdemo.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/orders")
public class OrderController {

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderItemDao orderItemDao;

    // 创建订单（包含订单项）
    @PostMapping
    public JsonResult<orders> createOrder(@RequestBody orders order) {
        try {
            // 保存订单主表
            orderDao.createOrder(order);

            // 保存订单项
            if (order.getItems() != null && !order.getItems().isEmpty()) {
                for (orderitem item : order.getItems()) {
                    item.setOrder_id(order.getOrder_id());
                    orderItemDao.createOrderItem(item);
                }
            }

            return JsonResult.success(order);
        } catch (Exception e) {
            return JsonResult.error("创建订单失败: " + e.getMessage());
        }
    }

    // 获取订单详情（包含订单项）
    @GetMapping("/{id}")
    public JsonResult<orders> getOrderById(@PathVariable int id) {
        try {
            orders order = orderDao.getOrderById(id);
            if (order == null) {
                return JsonResult.error("订单不存在");
            }

            // 获取关联的订单项
            List<orderitem> items = orderItemDao.getItemsByOrderId(id);
            order.setItems(items);

            return JsonResult.success(order);
        } catch (Exception e) {
            return JsonResult.error("获取订单详情失败: " + e.getMessage());
        }
    }

    // 更新订单状态
    @PutMapping("/{id}/status")
    public JsonResult<orders> updateOrderStatus(@PathVariable int id, @RequestBody Map<String, String> statusMap) {
        try {
            String newStatus = statusMap.get("status");
            if (newStatus == null || newStatus.isEmpty()) {
                return JsonResult.error("状态不能为空");
            }

            int result = orderDao.updateOrderStatus(id, newStatus);
            if (result > 0) {
                return JsonResult.success("订单状态更新成功");
            } else {
                return JsonResult.error("订单状态更新失败");
            }
        } catch (Exception e) {
            return JsonResult.error("更新订单状态失败: " + e.getMessage());
        }
    }

    // 删除订单（同时删除关联的订单项）
    @DeleteMapping("/{id}")
    public JsonResult<orders> deleteOrder(@PathVariable int id) {
        try {
            // 先删除订单项
            orderItemDao.deleteItemsByOrderId(id);

            // 再删除订单
            int result = orderDao.deleteOrder(id);
            if (result > 0) {
                return JsonResult.success("订单删除成功");
            } else {
                return JsonResult.error("订单删除失败");
            }
        } catch (Exception e) {
            return JsonResult.error("删除订单失败: " + e.getMessage());
        }
    }

    // 获取订单金额统计
    @GetMapping("/stats/amount")
    public JsonResult<Map<String, Object>> getOrderAmountStats(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {

        try {
            Map<String, Object> stats = orderDao.getOrderAmountStats(startDate, endDate);
            return JsonResult.success(stats);
        } catch (Exception e) {
            return JsonResult.error("获取订单统计失败: " + e.getMessage());
        }
    }

    //获取全部订单
    @GetMapping("/allproduct")
    public JsonResult<Object> getAllProduct() {
        try {
            List<orders> orders = orderDao.getAllOrders();
            return  JsonResult.success(orders);
        }catch (Exception e){
            return JsonResult.error("获取全部订单失败");
        }
    }

    // 搜索客户
    @GetMapping("/search")
    public ResponseEntity<List<orders>> searchProduct(
            @RequestParam(required = false) String orderNo,
            @RequestParam(required = false) Integer custId,
            @RequestParam(required = false) String status) {

        List<orders> orders = orderDao.searchOrderList(orderNo, custId, status);
        return ResponseEntity.ok(orders);
    }
}
